<template>
  <div class="common-layout">
    <el-container>
      <el-main class="main">
        <el-divider />
        <el-table :data="orderList" stripe style="width: 100%">
      <el-table-column prop="productOrderCode" label="订单编号" />
       <el-table-column prop="productTitle" label="商品名称" />
      <el-table-column prop="productOrderReceiver" label="收货人" />
      <el-table-column prop="productOrderMobile" label="联系电话" />
      <el-table-column label="收货地址">
        <template #default="scope">
          {{ scope.row.productOrderDetailAddress }}
        </template>
      </el-table-column>
      <el-table-column prop="productOrderTotalPrice" label="订单金额" />
      <el-table-column prop="productOrderPayDate" label="下单时间" />
      <el-table-column  label="订单状态" >
      <template #default="scope">
        <el-tag v-if="scope.row.productOrderStatus === '退货中'" type="warning">退货中</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '退货成功'" type="info">退货成功</el-tag>
        <el-tag v-else-if="scope.row.productOrderStatus === '退货失败'" type="danger">退货失败</el-tag>
      </template>
      </el-table-column>
      <el-table-column label="操作" width="300">
        <template #default="scope">

           <el-button
            v-if="scope.row.productOrderStatus === '退货中'"
            size="small"
            type="warning"
            @click="lookReturnReason(scope.row)">
            审核介入
          </el-button>
          <el-button
            size="small"
            @click="viewOrderDetail(scope.row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>



    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="dialogVisible"
      width="600px"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="订单编号">{{ currentOrder.productOrderCode }}</el-descriptions-item>
        <el-descriptions-item label="收货人">{{ currentOrder.productOrderReceiver }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentOrder.productOrderMobile }}</el-descriptions-item>
        <el-descriptions-item label="收货地址">{{ currentOrder.productOrderDetailAddress }}</el-descriptions-item>
        <el-descriptions-item label="邮政编码">{{ currentOrder.productOrderPost }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">￥{{ currentOrder.productOrderTotalPrice }}</el-descriptions-item>
        <el-descriptions-item label="下单时间">{{ formatDate(currentOrder.productOrderPayDate) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">{{ currentOrder.productOrderStatus }}</el-descriptions-item>
        <el-descriptions-item label="买家留言">{{ currentOrder.productOrderItems[0]?.productOrderItemUserMessage || '无' }}</el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

       <!-- 退货申请查看对话框 -->
    <el-dialog v-model="dialogFormVisible" title="退货申请原因" width="500">
      <el-form :model="form">
        <el-form-item label="原因"  >
            <el-select v-model="form.reason" placeholder="请选择退货原因" disabled>
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="描述" >
          <el-input v-model="form.description"  disabled/>
        </el-form-item>
      </el-form>
      <template #footer>
       <el-button
            size="small"
            type="success"
            @click="approveReturn(form.productOrderCode)">
            同意
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="rejectReturn(form.productOrderCode)">
            驳回
          </el-button>
      </template>
    </el-dialog>
      </el-main>
       <el-footer class="footer"
        ><div class="demo-pagination-block">
          <el-pagination
            v-model:current-page="currentPage"
            :page-size="pageSize"
            :size="size"
            layout="total, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          /></div
      ></el-footer>
    </el-container>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage,  } from "element-plus";
import instance from "@/utils/request";

// 订单列表
const orderList = ref([]);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const size = ref("large");
const total = ref(0);

// 对话框相关
const dialogVisible = ref(false);
const currentOrder = ref({});
const dialogFormVisible = ref(false);
const options = ref([]);
const form = ref({
  productOrderCode: null,
  productTitle: '',
  reason: '',
  description: ''
});

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 退货申请原因获取
const getReturnReasons = async () => {
  try {
    const response = await instance.get("/reason/userList");
    if (response.data.code === 200) {
      options.value = response.data.data.map(item => ({
        value: item.id,
        label: item.reason
      }));
    } else {
      ElMessage.error(response.data.message || "获取退货原因失败");
    }
  } catch (error) {
    console.error("获取退货原因出错:", error);
    ElMessage.error("获取退货原因失败");
  }
};

// 查看退货原因
const lookReturnReason = async(order) => {
  const response = await instance.get(`/returnRecords/getReturnRecordsByCode?code=${order.productOrderCode}`);
  if (response.data.code === 200) {
    form.value.productOrderCode = response.data.data.productOrderCode;
    form.value.reason = Number(response.data.data.reason);
    form.value.description = response.data.data.description;
    dialogFormVisible.value = true;
  } else {
    ElMessage.error("获取退货原因失败");
  }
};

// 获取订单列表
const getReturningOrderList = async () => {
  try {
    // 使用新的API端点和分页参数
    const response = await instance.get("/order/getReturningOrder", {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    });

    if (response.data.code === 200) {
      orderList.value = response.data.data.records;
      total.value = response.data.data.total;
    } else {
      ElMessage.error(response.data.message || "获取订单列表失败");
    }
  } catch (error) {
    console.error("获取订单列表出错:", error);
    ElMessage.error("获取订单列表失败");
  }
};

// 查看订单详情
const viewOrderDetail = (order) => {
  currentOrder.value = order;
  dialogVisible.value = true;
};



// 同意退货
const approveReturn = async(productOrderCode) => {
    const number=7; // 假设同意退货后状态变为退货成功
    try {
      const response = await instance.post("/order/updateOrderStatus", {
        productOrderCode: productOrderCode,
        productOrderStatus: number
      });
      if (response.data.code === 200) {
        ElMessage.success('同意退货成功');
        dialogFormVisible.value = false;
        getReturningOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response.data.message || "同意退货失败");
      }
    } catch (error) {
      console.error("同意退货出错:", error);
      ElMessage.error("同意退货失败");
    }
};

// 驳回退货
const rejectReturn = async(productOrderCode) => {
    console.log(productOrderCode);
    const number=9; // 假设驳回退货后状态变为退货失败
    try {
      const response = await instance.post("/order/updateOrderStatus", {
        productOrderCode: productOrderCode,
        productOrderStatus: number
      });
      if (response.data.code === 200) {
        ElMessage.success('驳回退货成功');
        dialogFormVisible.value = false;
        getReturningOrderList(); // 刷新订单列表
      } else {
        ElMessage.error(response.data.message || "驳回退货失败");
      }
    } catch (error) {
      console.error("驳回退货出错:", error);
      ElMessage.error("驳回退货失败");
    }
};

// 分页相关方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  getReturningOrderList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  getReturningOrderList();
};

// 组件挂载时获取订单列表
onMounted(() => {
  getReturningOrderList();
  getReturnReasons();
});
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
.main {
  background-color: rgb(255, 255, 255);
  padding: 20px 20px;
  height: calc(84vh - 30px);
}
.footer {
  background-color: rgb(255, 255, 255);
  padding: 12px 20px;
  border-bottom: 1px solid #eee;
  margin-top: 15px;
}
.demo-pagination-block {
  display: flex;
  justify-content: flex-end;
}
</style>
